<?php

class Server extends Actor
{ 
    //没用
    public static function start($args){ 
        return static::spawn_opt([$class,'init'],$args,[
            'addr'=>'service' 
        ]);
    }   
    //没用 
    public static function start_link($args){
        return static::spawn_opt([$class,'init'],$args,[
            'addr'=>'service','link'=>self::self(), 
        ]);
    }
    public function __construct(){ parent::__construct(); }
    public function __destruct(){  parent::__destruct(); exit; }
    
    public function after($result){  
        $this->trapexit(true);
        while(1) yield $this->receive(function($atom){
            switch ($atom[0]) {
                case 'EXIT':
                    exit('eeeeeeeeeeeeeeeeeeeeeeeee');
                    break;
                case 'case':
                    $this->handle_case($atom[1]);
                    return true;
                case 'call':
                    co(function()use($atom){
                        $result = yield $this->handle_call($atom[1]);
                        Booru::clientCase($atom[2],['resolve',$atom[3],$result]);
                    });
                    return true;
                default:
                    $this->handle_info($atom);
                    return true;
            } 
        }); 
    }
    
    public static function case($coid,$atom){
        preg_match('/([\d\.]+:\d+)#(\w+)/',$coid,$arr);
        return Booru::clientCase($arr[1],['send',$coid,['case',$atom]]);
    }
    public static function call(){
        $defer = Booru::channel($addr,$tick);
        preg_match('/([\d\.]+:\d+)#(\w+)/',$coid,$arr);
        Booru::clientCase($arr[1],['send',$coid,['call',$atom,$addr,$tick] ]);
        return $defer;
    }

    public function init(){
        return;
    }
    public function handle_case(){
        return;
    }
    public function handle_call(){
        return;
    }
    public function handle_info(){
        return;
    }
}

// class Gen { 
//     public static function start($fn, $args = [] )
//     {
//         \Proc::fock(function () use($fn,$args) {
//             Booru::connectServer('service');
//             Actor::spawn_opt(function()use($fn,$args){
//                 $this->trapexit(true);
//                 yield Action::spawn_opt($fn,$args,[
//                     'link'=>$this->coid
//                 ]);
//                 yield $this->receive();
//                 exit;
//             });
//         });
//     } 
// }